
dataset_documenter = function(varname, 
                              title = "(varname) dataset", 
                              description = "", 
                              details = "", 
                              seealso = "",
                              saveinpackage = TRUE) {
  
  # save very basic documentation for a dataset ####
  
  if (missing(title)) {
    title = paste0("#' @title ", varname,  " dataset\n" )
  } else{
    title = paste0("#' @title ", title,  "\n" )
  }
  
  if (description != "") {description = paste0("#' @description ", description,  "\n" )}
  
  if (details != "") {details = paste0("#' @details ", details,  "\n" )}
  if (seealso != "") {seealso = paste0("#' @seealso ", seealso,  "\n" )}
  
  # if dataset saved in pkg via use_data then the last line of the documentation file should be the name of the dataset in quotes.
  # if dataset NOT saved in pkg, but to be posted on pins board, then last line of doc file should be NULL without quotes,
  #   so it can create documentation as .Rd file without the object being available as something exported by the pkg.
  if (saveinpackage) {
    varnametext_or_null <- paste0("'", varname,"'")
  } else {
    varnametext_or_null <- "NULL"  
    }
  
  filecontents <- paste0(
    "\n# DO NOT EDIT THIS FILE - THIS DOCUMENTATION WAS CREATED BY A SCRIPT - see EJAM/data-raw/datacreate_",varname,".R or similar files\n\n",
    "#' @name ", varname, "
#' @docType data\n",
    title,
    description,
    details,
    seealso,
    varnametext_or_null
  )
  
  # save the .R file, but prefix documentation file names with "data_"
  writeChar(filecontents, con = paste0("./R/data_", varname, ".R"))
  
  # use rstudioapi to insert some insignificant text at the start of the document
  # because github had a problem where the .R file was treated as a binary object after writeChar() and this fixes the issue.
  rstudioapi::documentOpen(paste0("./R/data_", varname, ".R"))
  rstudioapi::insertText(c(1, 1), "# \n")
  rstudioapi::documentSave()
  rstudioapi::documentClose()
}
